package com.py.credit.service.impl;

import com.py.credit.common.ServiceException;
import com.py.credit.dao.ContentDao;
import com.py.credit.dao.RuleBindingDao;
import com.py.credit.entity.AreaEntity;
import com.py.credit.entity.SContentInfo;
import com.py.credit.entity.TableResult;
import com.py.credit.entity.common.TreeObj;
import com.py.credit.service.ContentService;
import com.py.credit.service.DeptService;
import com.py.credit.utils.SQLBuilder;
import com.py.framework.core.common.Page;
import com.py.framework.core.entity.SysOfficeEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private ContentDao contentDao;

    @Autowired
    private DeptService deptService;

    @Autowired
    private RuleBindingDao ruleBindingDao;

    @Override
    @Transactional
    public void addCommonContent(SContentInfo sContentInfo, List<TreeObj> nodeList) {

        int tableNum = 0;

        int colNum = 0;

        for (TreeObj treeObj : nodeList) {

            if ("T".equals(treeObj.getType())) {

                tableNum++;

            } else if ("M".equals(treeObj.getType())) {

                colNum++;

            }

        }

        sContentInfo.setColNum(colNum);
        sContentInfo.setTableNum(tableNum);
        sContentInfo.setStatus("N");
        contentDao.addCommonContentInfo(sContentInfo);
        contentDao.addCommonContent(nodeList, sContentInfo.getId());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCommonContentStatus(String status, int id) {

        contentDao.forbiddenCommonContent(id);
        contentDao.updateCommonContentStatus(status, id);

    }

    @Override
    @Transactional
    public void addBookCommonContent(SContentInfo sContentInfo, List<TreeObj> contentNode) {

        int tableNum = 0;

        int colNum = 0;

        for (TreeObj treeObj : contentNode) {

            if ("T".equals(treeObj.getType())) {

                tableNum++;

            } else if ("M".equals(treeObj.getType())) {

                colNum++;

            }

        }

        sContentInfo.setColNum(colNum);

        sContentInfo.setTableNum(tableNum);

        contentDao.addBookCommonContentInfo(sContentInfo);

        contentDao.addBookCommonContent(contentNode, sContentInfo.getId());
    }

    @Override
    public List<TreeObj> getCommonContentTree() {
        return contentDao.selectCommonContentTree();
    }

    @Override
    @Transactional
    public void bookContent(long regionId, int contentId, long userId, long deptId) {

        contentDao.delContentRegion(regionId, contentId);

        contentDao.addContentRegion(regionId, contentId, userId, deptId);

    }

    @Override
    public List<TreeObj> getCommonContentTree(String rootId, String sharingType,String informationType) {

        return contentDao.selectCommonContentInUse(rootId, sharingType,informationType);
    }

    @Override
    @Transactional
    public void delBookContent(String ids) {

        String[] idArray = ids.split(",");
        contentDao.delBookContentInfo(idArray);
        contentDao.delBookContent(idArray);

    }

    @Override
    public List<Map<String, Object>> getBookContentListForPage(List<String> showColumns, String[] additioanlColumns,
                                                               String condition, Page page, long regionId) {
        if (CollectionUtils.isEmpty(showColumns)) {

            throw new ServiceException("至少选择一列导出");

        }
        List<String> conditions = SQLBuilder.createConditionSql(condition);
        return contentDao.selectBookContentListByConditionForPage(showColumns, additioanlColumns, conditions, page,
                regionId);
    }

    @Override
    @Transactional
    public void updateBookContent(SContentInfo sContentInfo, List<TreeObj> nodeList) {

        String[] ids = {String.valueOf(sContentInfo.getId())};

        int tableNum = 0;

        int colNum = 0;

        for (TreeObj treeObj : nodeList) {

            if ("T".equals(treeObj.getType())) {

                tableNum++;

            } else if ("M".equals(treeObj.getType())) {

                colNum++;

            }

        }
        sContentInfo.setTableNum(tableNum);
        sContentInfo.setColNum(colNum);
        contentDao.updateBookContent(sContentInfo);
        contentDao.delBookContent(ids);
        contentDao.addBookCommonContent(nodeList, sContentInfo.getId());

    }

    @Override
    public List<TreeObj> getBoookContentDetail(int id) {

        return contentDao.selectBoookContentDetail(id);
    }

    @Override
    public SContentInfo getBookContentInfo(int id) {

        return contentDao.selectBookContenInfo(id);
    }

    @Override
    public void updateBookContentStatus(String id, String status) {
        contentDao.updateBookContentStatus(id, status);

    }

    @Override
    public List<Map<String, Object>> getSubscriptionInfo(String id) {

        return contentDao.selectSubscriptionInfo(id);
    }

    @Override
    @Transactional
    public void addCommonContent(SContentInfo sContentInfo) {

        List<TreeObj> dbNodes = contentDao.selectDbNode();
        List<TreeObj> deptNodes = new ArrayList<TreeObj>();
        List<SysOfficeEntity> topLevelDept = deptService.getRootOffices();

        for (TreeObj node : dbNodes) {

            for (SysOfficeEntity dept : topLevelDept) {

                TreeObj treeObj = new TreeObj();
                treeObj.setId(node.getId() + "_" + dept.getId());
                treeObj.setName(dept.getOfficeName());
                treeObj.setCode(dept.getOfficeCode());
                treeObj.setType("D");
                treeObj.setRootId(node.getId());
                treeObj.setpId(node.getId());
                treeObj.setSort(dept.getOrderBy());
                deptNodes.add(treeObj);

            }

        }
        List<TreeObj> cubeNodes = contentDao.selectCubeNodes();
        List<TreeObj> metricNodes = contentDao.selectMetricNodes(cubeNodes);
        dbNodes.addAll(deptNodes);
        dbNodes.addAll(cubeNodes);
        dbNodes.addAll(metricNodes);
        contentDao.clearCommonContent();
        contentDao.clearCommonContentInfo();
        contentDao.addCommonContentInfo(sContentInfo);
        contentDao.addCommonContent(dbNodes, sContentInfo.getId());
        contentDao.forbiddenCommonContent(sContentInfo.getId());

    }

    @Override
    public TableResult getTableColumns(Integer tableId, Integer contentId, String tipId) {

        return contentDao.selectTableColumns(tableId, contentId, tipId);
    }

    @Override
    public List<TreeObj> getBoookContentByRegionId(String regionId) {

        return contentDao.selectBoookContentByRegionId(regionId);
    }

    @Override
    public List<TreeObj> getCommonContent(String kId) {

        return contentDao.selectCommonContent(kId);
    }

    @Override
    public SContentInfo getCommonContentInfo() {

        return contentDao.selectCommonContentInfo();
    }

    @Override
    public List<Map<String, Object>> getCommonContentResouceNum(String kId) {

        return contentDao.selectContentResouceNum(kId);
    }

    @Override
    public List<Map<String, Object>> getBookContentResouceNum(String kId, String regionKey) {

        return contentDao.selectBoookContentReourceNumByRegionId(kId, regionKey);
    }

    @Override
    public List<Map<String, Object>> getCommonContentTableNum() {

        return contentDao.selectCommonContentTableNum();
    }

    @Override
    public List<TreeObj> getCommonContentDept() {

        return contentDao.selectCommonContentDept();
    }

    @Override
    public List<TreeObj> getOriginalContentTree() {
        List<TreeObj> dbNodes = contentDao.selectDbNode();
        List<TreeObj> deptNodes = new ArrayList<TreeObj>();
        List<SysOfficeEntity> topLevelDept = deptService.getRootOffices();
        for (TreeObj node : dbNodes) {

            for (SysOfficeEntity dept : topLevelDept) {

                TreeObj treeObj = new TreeObj();
                treeObj.setId(node.getId() + "_" + dept.getId());// 100000_21
                treeObj.setName(dept.getOfficeName());
                // 发改委
                treeObj.setCode(dept.getOfficeCode());
                // gsj
                treeObj.setType("D");
                treeObj.setRootId(node.getId());
                // 100000
                treeObj.setpId(node.getId());
                // 100000
                treeObj.setSort(dept.getOrderBy());
                // 1
                deptNodes.add(treeObj);

            }

        }
        List<TreeObj> cubeNodes = contentDao.selectCubeNodes();
        List<TreeObj> filterCubes = filterCubes(cubeNodes, deptNodes);

        dbNodes.addAll(deptNodes);
        dbNodes.addAll(filterCubes);

        if (!CollectionUtils.isEmpty(filterCubes)) {
            List<TreeObj> metricNodes = contentDao.selectMetricNodes(filterCubes);
            dbNodes.addAll(metricNodes);
        }

        return dbNodes;
    }

    /**
     * @param cubeNodes
     * @param topLevelDept
     */
    private List<TreeObj> filterCubes(List<TreeObj> cubeNodes, List<TreeObj> topLevelDept) {

        List<TreeObj> filter = new ArrayList<TreeObj>();

        for (TreeObj cubeNode : cubeNodes) {

            for (TreeObj deptNode : topLevelDept) {

                if (cubeNode.getpId().equals(deptNode.getId())) {

                    filter.add(cubeNode);

                    continue;

                }

            }

        }

        return filter;

    }

    @Override
    public List<Map<String, Object>> getCommonContentListForPage(List<String> showColumns, String[] additioanlColumns,
                                                                 String condition, Page page) {
        if (CollectionUtils.isEmpty(showColumns)) {

            throw new ServiceException("至少选择一列导出");

        }
        List<String> conditions = SQLBuilder.createConditionSql(condition);
        return contentDao.selectCommonContentListByConditionForPage(showColumns, additioanlColumns, conditions, page);
    }

    @Override
    public List<TreeObj> getCommonContentDetail(int id) {

        return contentDao.selectCommonContentDetail(id);
    }

    @Override
    public SContentInfo getCommonContentInfo(int id) {

        return contentDao.selectCommonContentInfoById(id);
    }

    @Override
    public List<TreeObj> getCommonContentTree(int id) {

        return contentDao.selectEditCommonContentTree(id);

    }

    @Override
    @Transactional
    public void updateCommonContent(SContentInfo sContentInfo, List<TreeObj> nodeList) {

        String[] ids = {String.valueOf(sContentInfo.getId())};

        int tableNum = 0;

        int colNum = 0;

        for (TreeObj treeObj : nodeList) {

            if ("T".equals(treeObj.getType())) {

                tableNum++;

            } else if ("M".equals(treeObj.getType())) {

                colNum++;

            }

        }
        sContentInfo.setTableNum(tableNum);
        sContentInfo.setColNum(colNum);
        contentDao.updateCommonContent(sContentInfo);
        contentDao.delCommonContent(ids);
        contentDao.addCommonContent(nodeList, sContentInfo.getId());

    }

    @Override
    public void delCommonContent(String ids) {
        String[] idArray = ids.split(",");
        contentDao.delCommonContentInfo(idArray);
        contentDao.delCommonContent(idArray);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkCommonContent(String id, String checkStatus) {
        //如果审核通过
        if ("P".equals(checkStatus)) {
            //查询出版本信息
            SContentInfo sContentInfo = contentDao.selectCommonContentInfoById(Integer.valueOf(id));
            //获取旧启用版本的id
            Integer editionId = ruleBindingDao.selectCurrentContentVersion();
            if (editionId != null) {
                //更新字段绑定
                List<HashMap<String, Object>> columnData = ruleBindingDao.selectVersionBindColumnData(editionId,id);
                if (!columnData.isEmpty()) {
                    ruleBindingDao.updateVersionBindColumnData(columnData, id);
                }
                //更新表绑定
                List<HashMap<String, Object>> tableData = ruleBindingDao.selectVersionBindTableData(editionId);
                if (!tableData.isEmpty()) {
                    ruleBindingDao.updateVersionBindTableData(tableData, id);
                }
            }
            if (sContentInfo != null) {
                //如果审核通过后立即使用
                if ("Y".equals(sContentInfo.getUseImmediately())) {
                    //状态设置为Y
                    contentDao.updateCommonContentStatus("Y", Integer.valueOf(id));
                    //旧状态改为N
                    contentDao.forbiddenCommonContent(Integer.valueOf(id));
                }
            }
        }
        //修改版本审核的结果
        contentDao.checkCommonContent(id, checkStatus);

    }

    @Override
    public TableResult getExcel(int tableId, String title) {

        return contentDao.selectExcel(tableId, title);
    }

	
	
	@Override
	public List<AreaEntity> getAllArea() {
		
		return contentDao.getAllArea();
	}

}
